<template>
  <prism-editor
    class="code-editor"
    v-model="fileContent"
    :highlight="highlighter"
    line-numbers
  />
</template>
<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from "vue";
import { api, sseClose, previewFile } from "@/utils/api";
import { CodeFile } from "@/types/interfaces";
import { TOKEN_STORAGE } from "@/types/constant";
import { useMessage } from "naive-ui";
import { PrismEditor } from "vue-prism-editor";
import "vue-prism-editor/dist/prismeditor.min.css";
import * as Prism from "prismjs";
import "prismjs/themes/prism.css";
// 信息提示
const message = useMessage();
// 预览文件
const { file } = defineProps<{ file: CodeFile }>();
// 文件内容
const fileContent = ref<string>("");
// SSE 客户端
let eventSource: EventSource | null = null;
// 挂载初始化 SSE
onMounted(() => {
  initSSE();
});
// 卸载关闭 SSE
onBeforeUnmount(() => {
  closeSSE();
});
// 初始化 SSE
const initSSE = () => {
  fileContent.value = "";
  eventSource = new EventSource(
    api.sseConnect + localStorage.getItem(TOKEN_STORAGE)
  );
  eventSource.onopen = (_event) => {};
  eventSource.addEventListener("connected", (_event) => {
    preview();
  });
  eventSource.onmessage = (event) => {
    fileContent.value = fileContent.value.concat(event.data || "") + '\n';
  };
  eventSource.onerror = (_event) => {
    closeSSE();
  };
};
// 关闭 SSE
const closeSSE = () => {
  if (eventSource != null) {
    eventSource.close();
    sseClose();
    eventSource = null;
  }
};
// 预览
const preview = async () => {
  const res = await previewFile(file.index);
  if (res.code !== 200) {
    message.error(res.message || "预览失败");
  }
};
// 高亮
const highlighter = (code: string) => {
  const split =  file.name.split(".");
  const fileType = split[split.length - 1]
  return Prism.highlight(code, Prism.languages[fileType], fileType);
};
</script>
<style scoped>
/* required class */
.code-editor {
  /* we dont use `language-` classes anymore so thats why we need to add background and text color manually */
  background: #2d2d2d;
  color: #ccc;

  /* you must provide font-family font-size line-height. Example: */
  font-family: Fira code, Fira Mono, Consolas, Menlo, Courier, monospace;
  font-size: 14px;
  line-height: 1.5;
  padding: 5px;
}

/* optional class for removing the outline */
.prism-editor__textarea:focus {
  outline: none;
}
</style>
